package com.eshop.controller;

import com.eshop.model.Address;
import com.eshop.model.User;
import com.eshop.service.Impl.UserCenterServiceImpl;
import com.eshop.service.UserCenterService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

@WebServlet("/user")
public class UserController extends HttpServlet {
    UserCenterService userCenterService = new UserCenterServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        String action = req.getParameter("action");

        try {
            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void userInformation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            int userSex = Integer.parseInt(req.getParameter("userSex"));
            int age = Integer.parseInt(req.getParameter("age"));
            String email = req.getParameter("email");
            assert age > 0;

            User user = (User) req.getSession().getAttribute("_LOGIN_USER_");

            user.setUser_sex(userSex);
            user.setUser_age(age);
            user.setUser_email(email);

            userCenterService.updateUser(user);
            req.getSession().setAttribute("_LOGIN_USER_",user);
            resp.getWriter().write("{\"updateInformation\":true}");
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("{\"updateInformation\":false,\"msg\":\"格式错误\"}");
        }
    }

    protected void userPasswordChange(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String newPasswordConfirm = req.getParameter("newPasswordConfirm");

        User user = (User) req.getSession().getAttribute("_LOGIN_USER_");

        if (!user.getUser_pass().equals(oldPassword)) {
            resp.getWriter().write("{\"updatePassword\":false,\"msg\":\"原密码错误\"}");
        }
        else if (!newPassword.equals(newPasswordConfirm)) {
            resp.getWriter().write("{\"updatePassword\":false,\"msg\":\"两次输入密码不同\"}");
        }
        else if (newPassword.trim().length()==0 || newPassword.length()!=newPassword.trim().length()) {
            resp.getWriter().write("{\"updatePassword\":false,\"msg\":\"密码不能有空格\"}");
        }
        else {
            user.setUser_pass(newPassword);
            userCenterService.updateUser(user);
            req.getSession().setAttribute("_LOGIN_USER_",user);
            resp.getWriter().write("{\"updatePassword\":true}");
        }
    }

    protected void getUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            User user = (User)req.getSession().getAttribute("_LOGIN_USER_");
            List<Address> addressList = userCenterService.getAddressByUserId(user.getUser_id());
            req.setAttribute("addressList",addressList);
            req.getRequestDispatcher("/pages/user/userCenter.jsp?action=userDeliveryAddress").forward(req, resp);
        }catch (Exception e){
            e.printStackTrace();
            req.getRequestDispatcher("/pages/user/userCenter.jsp?action=userInformation").forward(req, resp);
        }
    }

    protected void addOrUpdateUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String addressId = req.getParameter("myAddressModalAddressId");
        String addressProvince = req.getParameter("myAddressModalAddressProvince");
        String addressCity = req.getParameter("myAddressModalAddressCity");
        String addressArea = req.getParameter("myAddressModalAddressArea");
        String addressContent = req.getParameter("myAddressModalAddressContent");
        String addressReceiver = req.getParameter("myAddressModalAddressReceiver");
        String addressTel = req.getParameter("myAddressModalAddressTel");
        if (addressId.trim().length() == 0){
            User user = (User)req.getSession().getAttribute("_LOGIN_USER_");
            Address address = new Address(0,user.getUser_id(),addressProvince,addressCity,addressArea,addressContent,addressReceiver,addressTel,0);
            userCenterService.addAddress(address);
        }
        else {
            Address address = userCenterService.getAddressByAddressId(Integer.parseInt(addressId));
            address.setAddr_province(addressProvince);
            address.setAddr_city(addressCity);
            address.setAddr_area(addressArea);
            address.setAddr_content(addressContent);
            address.setAddr_receiver(addressReceiver);
            address.setAddr_tel(addressTel);
            userCenterService.updateAddress(address);
        }
//        resp.sendRedirect(req.getContextPath()+"/user?action=getUserDeliveryAddress");
    }

    protected void deleteUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int addressId = Integer.parseInt(req.getParameter("addressID"));
        userCenterService.deleteAddressByAddressId(addressId);
    }

    protected void defaultUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int addressId = Integer.parseInt(req.getParameter("addressID"));
        User user = (User)req.getSession().getAttribute("_LOGIN_USER_");

        userCenterService.updateDefaultAddress(user.getUser_id(),addressId);

        resp.sendRedirect(req.getContextPath()+"/user?action=getUserDeliveryAddress");
    }
}
